#include "dialog.h"
#include "ui_dialog.h"
#include <QMessageBox>

const quint16 port = 6666;
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    //1.1 初始化套接字
    udpSocket = new QUdpSocket(this);\
    //1.2绑定
    bool res = udpSocket->bind(port);
    if(!res)
    {
        QMessageBox::information(this,"error","bind error");
        return ;
    }
    //1.3数据接收曹处理
    connect(udpSocket,SIGNAL(readyRead()),
            this,SLOT(ReadMsg()));
}

Dialog::~Dialog()
{
    delete udpSocket;
    delete ui;
}

void Dialog::ReadMsg()
{
    //1.4准备接收,判断io缓冲是否有数据
    //如果有数据包返回true
     while(udpSocket->hasPendingDatagrams())
     {

         QByteArray da;
         //获取到数据报的大小
         da.resize(udpSocket->pendingDatagramSize());
        //1.5接收数据
         udpSocket->readDatagram(da.data(),da.size());
         QString msg = da.data();
         ui->textEdit->insertPlainText(msg);
     }
}
